package com.oa.modules.approvalsec1.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;

import cn.hutool.core.date.DateUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.common.utils.FreemarkerUtil;
import com.oa.common.utils.PageUtils;
import com.oa.common.utils.R;
import com.oa.modules.approvalsec1.dao.ArchivesDao;
import com.oa.modules.approvalsec1.entity.ArchivesEntity;
import com.oa.modules.approvalsec1.service.ArchivesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
//import oracle.jdbc.proxy.annotation.Post;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Author: Hankaicheng
 * @Date: 2022/3/25 10:36
 */
@RestController
@RequestMapping("/archives")
@Api(tags = "档案存放相关接口")
@Log4j2
public class ArchivesController {

    @Autowired
    private ArchivesService service;
    @Autowired
    private ArchivesDao archivesDao;

    public static String getId1(String year, String id, int size) {
        String id1 = year + id + "";
        if (size < 10) {
            id1 = id1 + "000" + size;
        } else if (size < 100) {
            id1 = id1 + "00" + size;
        } else if (size < 1000) {
            id1 = id1 + "0" + size;
        } else if (size < 10000) {
            id1 = id1 + "" + size;
        } else if (size < 100000) {
            id1 = id1 + size;
        }
        return id1;
    }


//    @ApiOperation(value = "列表，根据档案id前3位进行分类")
//    @GetMapping("/list/{id}")
//    public R list(@PathVariable("id") String id){
//        PageUtils page = service.queryPage(id);
//        return R.ok().put("data",page);
//    }

    @PostMapping(value = "/listPage")
    @ApiOperation(value = "列表")
    public R queryPage(@RequestParam Map<String, Object> params) {
        PageUtils page = service.queryPage(params);
        return R.ok().put("page", page);
//        return service.queryPage1(params);
    }

    @ApiOperation(value = "添加")
    @PostMapping("/save/{file_number}")
    public R save(@ApiParam("file_number前三位") @PathVariable("file_number") String file_number, @ApiParam("档案对象，file_number，StoreNumber，时间可以为空") @RequestBody ArchivesEntity entity) {
        entity.setId(UUID.randomUUID().toString());
        entity.setCreateDate(new Date());
        //filenumber为空，我们将追加生成
        if (StringUtils.isEmpty(entity.getFileNumber())) {
            Integer count = Integer.parseInt(archivesDao.count(file_number).toString());
            String id1 = getId(file_number, count + 1);
            String year = new SimpleDateFormat("yyyy").format(new Date()).toString().substring(2, 4);
            String id2 = getId1(year, file_number, count);
            entity.setFileNumber(id1);
            entity.setStoreNumber(id2);
        }
        boolean save = service.save(entity);
        if (save) {
            return R.ok("添加成功");
        }
        return R.error(500, "添加失败");
    }

    @ApiOperation(value = "修改")
    @PostMapping("/update")
    public R update(@ApiParam("id不能为空") @RequestBody ArchivesEntity entity) {
        entity.setUpdateDate(new Date());
        boolean b = service.updateById(entity);
        if (b) {
            return R.ok("修改成功");
        }
        return R.error(500, "修改失败");
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete/{id}")
    public R delete(@PathVariable("id") String id) {
        boolean b = service.removeById(id);
        if (b) {
            return R.ok("删除成功");
        }
        return R.error(500, "删除失败");

    }

    @ApiOperation(value = "根据id获取信息")
    @GetMapping("/info/{id}")
    public R infoId(@ApiParam("id") @PathVariable("id") String id) {
        ArchivesEntity entity = service.getById(id);
        if (entity != null) {
            return R.ok().put("data", entity);
        }
        return R.error(500, "查不到数据");
    }

    @ApiOperation("导出excel")
    @GetMapping(value = "/export")
    public void getExcel(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        PageUtils page = service.queryPage(params);
        ArrayList<ArchivesEntity> list = (ArrayList<ArchivesEntity>) page.getList();
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams((String) params.get("title"), (String) params.get("title")), ArchivesEntity.class, list);
        String fileName = URLEncoder.encode(((String) params.get("title") + DateUtil.format(new Date(), "yyyyMMdd")), "UTF-8").replaceAll("\\+", "%20");
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            log.error("下载文件失败!", e);
        }
//        PageUtils page = service.queryPage(params);
//        List<ArchivesEntity> list = (List<ArchivesEntity>) page.getList();
//        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("123", "测试", "测试"), ArchivesEntity.class, list);
//        System.out.println("123");
//        String fileName = URLEncoder.encode(("招商引资" + DateUtil.format(new Date(), "yyyyMMdd")), "UTF-8").replaceAll("\\+", "%20");
//        try {
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
//            OutputStream outputStream = response.getOutputStream();
//            workbook.write(outputStream);
//            outputStream.close();
//        } catch (Exception e) {
//            System.out.println("文件下载失败");
//        }

//        //设置默认文件名为当前时间：年月日时分秒
//        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
//        ExportParams params = new ExportParams(title + " (" + id + ")", title + " (" + id + ")", ExcelType.HSSF);
//        Workbook workbook = ExcelExportUtil.exportExcel(params, ArchivesEntity.class, aList);
//        ServletOutputStream out = null;
//        try {
//            //流形式
//            response.setHeader("content-type", "application/octet-stream");
//            //防止中文乱码
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(title + fileName + ".xls", "UTF-8"));
//            out = response.getOutputStream();
//            workbook.write(out);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (null != out) {
//                try {
//                    out.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
    }

    @ApiOperation(value = "导出word")
    @PostMapping(value = "/getDoc/{id}")
    public void getDoc(@ApiParam("file_number前三位") @PathVariable("id") String id, String title, HttpServletResponse response) {
        List<ArchivesEntity> records = service.allById(id);
        if (records != null && records.size() > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("title", title + "(" + id + ")");
            List<Map<String, Object>> list = new ArrayList<>();
            if (records != null && records.size() > 0) {
                for (int i = 0; i < records.size(); i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("fileNumber", records.get(i).getFileNumber());
                    map.put("windowNumber", records.get(i).getWindowNumber());
                    map.put("archivesName", records.get(i).getArchivesName());
                    map.put("storeNumber", records.get(i).getStoreNumber());
                    map.put("companyName", records.get(i).getCompanyName());
                    map.put("businessType", records.get(i).getBusinessType());
                    map.put("note", records.get(i).getNote());
                    list.add(map);
                }
            }
            dataMap.put("list", list);
            String templateName = "archivesEntity.ftl";
            String filePath = "D:\\freemarker";
            String fileName = System.currentTimeMillis() + "";
            try {
                FreemarkerUtil.createWord(dataMap, templateName, filePath, fileName, response);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("文件下载失败");
            }
        }
    }

    @ApiOperation(value = "导入档案数据")
    @PostMapping("/import/{id}")
    public R importArchives(@ApiParam("file_number前三位") @PathVariable("id") String id, MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<ArchivesEntity> archivesEntityList = ExcelImportUtil.importExcel(file.getInputStream(), ArchivesEntity.class, params);
        List<ArchivesEntity> list = archivesEntityList.stream().filter(e -> StringUtils.isNotEmpty(e.getArchivesName())).collect(Collectors.toList());
        ArrayList<ArchivesEntity> archivesEntities = new ArrayList<>();
        AtomicReference<String> fileNumer = new AtomicReference<>("");
        AtomicReference<String> windowNumber = new AtomicReference<>("");
//        long errorNumber = list.stream().filter(e -> StringUtils.isNotEmpty(e.getFileNumber()) && !e.getFileNumber().substring(0, 3).equals(id)).count();
        AtomicInteger repeatCount = new AtomicInteger();
//        if (errorNumber == list.size()) return R.error("导入失败");
        if (list != null && list.size() > 0) {
            list.forEach(item -> {
                if (StringUtils.isNotEmpty(item.getArchivesName())) {
                    item.setId(UUID.randomUUID().toString());
                    item.setCreateDate(new Date());
                    if (StringUtils.isNotEmpty(item.getFileNumber())) {
                        fileNumer.set(item.getFileNumber());
                    }
                    if (StringUtils.isNotEmpty(item.getWindowNumber())) {
                        windowNumber.set(item.getWindowNumber());
                    }
                    item.setFileNumber(fileNumer.get());
                    item.setWindowNumber(windowNumber.get());
                    ArchivesEntity one = service.getOne(new QueryWrapper<ArchivesEntity>().eq("ARCHIVES_NAME", item.getArchivesName()).eq("FILE_NUMBER", item.getFileNumber()));
                    if (one == null && item.getFileNumber().substring(0, 3).equals(id)) {
                        archivesEntities.add(item);
                    } else {
                        repeatCount.getAndIncrement();
                    }
                }
            });
            archivesEntities.removeIf(e -> StringUtils.isEmpty(e.getArchivesName()));
            archivesEntities.removeIf(e -> StringUtils.isNotEmpty(e.getArchivesName()) && !e.getFileNumber().substring(0, 3).equals(id));
            service.saveBatch(archivesEntities);
            if (archivesEntities == null || archivesEntities.size() == 0) {
                return R.error(500, "成功导入" + archivesEntities.size() + "，导入失败" + repeatCount.get());
            }
            return R.ok(0, "成功导入" + archivesEntities.size() + "，导入失败" + repeatCount.get());
        }
        return R.error(500, "导入失败");


//        ImportParams params = new ImportParams();
//        //去掉标题行
//        List<ArchivesEntity> archivesEntityList = service.allById(id);
//        int size = archivesEntityList.size()+1;
//        try {
//            List<ArchivesEntity> list = ExcelImportUtil.importExcel(file.getInputStream(), ArchivesEntity.class, params);
//            List<ArchivesEntity> list1 = new ArrayList<>();
//            String year = new SimpleDateFormat("yyyy").format(new Date()).toString().substring(2,4);
//            boolean flag = false;
//            String fileNumber = "";
//            String windowNumber="";
//            String storeNumber="";
//            for (ArchivesEntity archivesEntity : list) {
//                if (!StringUtils.isNotEmpty(archivesEntity.getStoreNumber())){
//                    continue;
//                }
//                //合并单元格只有一个对应fileNumber
//                if(StringUtils.isNotEmpty(archivesEntity.getFileNumber())){
//                    fileNumber=archivesEntity.getFileNumber();
//                }
//                //合并单元格只有一个对应windowNumber
//                if(StringUtils.isNotEmpty(archivesEntity.getWindowNumber())){
//                    windowNumber=archivesEntity.getWindowNumber();
//                }
//                //合并单元格只有一个对应windowNumber
//                if (StringUtils.isNotEmpty(archivesEntity.getStoreNumber())){
//                    storeNumber = archivesEntity.getStoreNumber();
//                }
//                archivesEntity.setFileNumber(fileNumber);
//                archivesEntity.setWindowNumber(windowNumber);
//                archivesEntity.setStoreNumber(storeNumber);
//                flag = false;
//                for (ArchivesEntity archivesEntity1 : archivesEntityList){
//                    //如果file_number和storeNumber一样说明事修改
//                    if(archivesEntity.getStoreNumber().equals( archivesEntity1.getStoreNumber())
//                            &&archivesEntity.getFileNumber().equals(archivesEntity1.getFileNumber())){
//                        archivesEntity.setUpdateDate(new Date());
//                        service.updateByFileNumber(archivesEntity);
//                        flag = true;
//                        break;
//                    }
//                }
//                if(flag){
//                    continue;
//                }
////               String id1 = getId(id, size);
////               String id2 = getId1(year,id, size);
//                archivesEntity.setId(UUID.randomUUID().toString());
//                archivesEntity.setCreateDate(new Date());
////               archivesEntity.setStoreNumber(id2);
//                list1.add(archivesEntity);
//                size++;
//            }
//            if (service.saveBatch(list1)){
//                return R.ok("导入成功!");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return R.error("导入失败！");
    }

    public String getId(String id, int size) {
        String id1 = id + "";
        if (size < 10) {
            id1 = id1 + "0000" + size;
        } else if (size < 100) {
            id1 = id1 + "000" + size;
        } else if (size < 1000) {
            id1 = id1 + "00" + size;
        } else if (size < 10000) {
            id1 = id1 + "0" + size;
        } else if (size < 100000) {
            id1 = id1 + size;
        }
        return id1;
    }

}
